<script setup>
import { computed } from 'vue';
import dayjs from 'dayjs';

const props = defineProps({
  category: {
    type: Object,
    required: true,
  },
  courses: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['select-course']);

const subtitle = computed(() => {
  if (!props.courses.length) {
    return '该课程暂无详细信息';
  }
  if (props.category?.title && props.category?.title !== props.courses[0]?.title) {
    return `包含 ${props.courses.length} 门课程`;
  }
  return props.courses[0]?.body || '点击查看详情';
});

const formatTime = (value) => {
  if (!value) return '暂无开课时间';
  const date = dayjs(value);
  return date.isValid() ? date.format('YYYY年MM月DD日 HH:mm') : '暂无开课时间';
};

const handleSelect = (course) => {
  emit('select-course', course);
};
</script>

<template>
  <el-card class="category-card" shadow="hover">
    <div class="category-card__header">
      <div>
        <h3>{{ category.title || '课程' }}</h3>
        <p>{{ subtitle }}</p>
      </div>
      <el-tag type="primary" effect="plain">课程</el-tag>
    </div>
    <el-divider />
    <div class="category-card__body">
      <el-empty v-if="!courses.length" description="暂无课程" />
      <ul v-else class="course-list">
        <li
          v-for="course in courses"
          :key="course.id"
          class="course-list__item"
        >
          <div class="course-list__info">
            <h4>{{ course.title }}</h4>
            <span>开课时间：{{ formatTime(course.startTime) }}</span>
          </div>
          <el-button type="primary" link @click="handleSelect(course)">
            查看详情
          </el-button>
        </li>
      </ul>
    </div>
  </el-card>
</template>

<style scoped>
.category-card {
  border-radius: 16px;
  overflow: hidden;
}

.category-card__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.category-card__header h3 {
  font-size: 20px;
  margin-bottom: 4px;
}

.category-card__header p {
  color: #666;
  font-size: 13px;
}

.course-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.course-list__item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f2f8;
}

.course-list__item:last-child {
  border-bottom: none;
}

.course-list__info h4 {
  font-size: 17px;
  margin-bottom: 6px;
}

.course-list__info span {
  font-size: 13px;
  color: #909399;
}
</style>
